package com.bba.manager.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bba.manager.common.model.order.Order;
import com.bba.manager.common.model.order.OrderDetails;
import com.bba.manager.common.model.order.VO.orderVO;
import com.bba.manager.order.mapper.OrderMapper;
import com.bba.manager.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zzy
 * @since 2025-08-12
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderDetailsServiceImpl orderDetailsServiceImpl;
    @Autowired
    private OpenFeignServiceImpl openFeignServiceImpl;
    @Autowired
    private OrderMapper orderMapper;



    @Override
    public Page listall() {
        List<Order> list = this.list();
        Page page =new Page<>();
        page.setRecords(list);
        page.setCurrent(1);
        page.setSize(10);
        return page;

    }
    @Override
    public BigDecimal getTotalPriceByDate(Integer employeeId, String dateStr) {
        LocalDate startDate;
        LocalDate endDate;

        // 日期范围判断
        if (dateStr.matches("\\d{4}")) { // 年
            startDate = LocalDate.of(Integer.parseInt(dateStr), 1, 1);
            endDate = startDate.plusYears(1);
        } else if (dateStr.matches("\\d{4}-\\d{2}")) { // 年月
            YearMonth ym = YearMonth.parse(dateStr);
            startDate = ym.atDay(1);
            endDate = ym.plusMonths(1).atDay(1);
        } else if (dateStr.matches("\\d{4}-\\d{2}-\\d{2}")) { // 年月日
            startDate = LocalDate.parse(dateStr);
            endDate = startDate.plusDays(1);
        } else {
            throw new IllegalArgumentException("日期格式不正确，应为 yyyy 或 yyyy-MM 或 yyyy-MM-dd");
        }

        // 用 QueryWrapper 执行聚合查询
        Map<String, Object> result = orderMapper.selectMaps(
                new QueryWrapper<Order>()
                        .select("SUM(total_price) as totalPrice")
                        .eq("employee_id", employeeId)
                        .ge("create_time", startDate.atStartOfDay())
                        .lt("create_time", endDate.atStartOfDay())
        ).stream().findFirst().orElse(null);

        BigDecimal totalPrice = result != null ? (BigDecimal) result.get("totalPrice") : BigDecimal.ZERO;
        return totalPrice != null ? totalPrice : BigDecimal.ZERO;
    }


}
